<template>
  <div
    class="userManage"
    :class="scroll.isFixed ? 'userManagefixed' : ''"
    id="userManage"
  >
    <!-- 功能按钮 -->
    <div class="userManage_button">
      <a-button class="addButton" type="primary" :disabled="creatAble" @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建
      </a-button>
      <a-button class="importButton" :disabled="importAble" @click="batchAddRecord"
        >批量导入</a-button
      >
      <a class="download-btn" :class="{ disable: downloadAble }" @click="downloadtemp"
        >下载导入模版</a
      >
    </div>
    <div class="select-content">
      <div class="select-item">
        <div class="title">关键词：</div>
        <a-input
          v-model:value="resData.name"
          placeholder="用户名或真实姓名"
          style="width: 241px;height:32px"
          allow-clear
          @blur="search"
          @pressEnter="search"
        >
        <template #suffix>
            <i
              class="iconfont icon-search"
              @click="search"
            ></i>
          </template>
        </a-input>
      </div>
      <div class="select-item">
        <div class="title">所属组织：</div>
        <a-tree-select
          class="AtreeSelect"
          v-model:value="selectOrgvalue"
          ref="usermanage_treeSelect"
          show-search
          :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
          allow-clear
          treeNodeFilterProp="name"
          :fieldNames="{
            children: 'children',
            label: 'name',
            value: 'id',
          }"
          tree-default-expand-all
          :tree-data="orgTreeDataHeader"
          @change="selectTreeDataHeader"
        >
        </a-tree-select>
      </div>
      <div v-show="!isOpen" class="select-item">
        <div class="title">关联的虚拟组织：</div>

        <a-select
          v-model:value="orgVirValue"
          :options="orgVirOptions"
          allow-clear
          @change="onSelectOrg"
        ></a-select>
      </div>
      <!-- <div v-show="!isOpen" class="select-item">
        <div class="title">人员密级：</div>
        <a-select
          v-model:value="sequrityValue"
          :options="sequrityOptions"
          allow-clear
          @change="onSelectSequrity"
        ></a-select>
      </div> -->
      <div v-show="!isOpen" class="select-item">
        <div class="title">状态：</div>
        <a-select
          v-model:value="statusHeaderValue"
          :options="statusOptions"
          allow-clear
          @change="selectHeaderStatus"
        ></a-select>
      </div>
      <div class="option-content">
        <a-button @click="resetOptions">重置</a-button>
        <!-- <a-button
          :style="{ 'margin-left': '8px' }"
          class="addButton"
          type="primary"
          @click="search()"
          >搜索</a-button
        > -->
        <div class="openorclose" @click="openorclose" v-show="!isOpen">
          <a>收起</a>
          <i class="iconfont icon-up" style="font-size: 24px"> </i>
        </div>
        <div class="openorclose" @click="openorclose" v-show="isOpen">
          <a>展开</a>
          <i class="iconfont icon-down" style="font-size: 24px"> </i>
        </div>
      </div>
    </div>
    <!-- 表格展示部分 -->
    <baseTable
      :columns="userManagesColumns"
      :dataSource="userData.records"
      :isSelect="true"
      :scroll="scroll"
      ref="userManageBaseTables"
      :isShowPagination="isShowPagination"
      :showCheckDelete="showCheckDelete"
      :total="userData.total"
      @changePage="changePage"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'isEnabled'">
          <a-switch
            @click="switchChange(record)"
            :disabled="record.id === userId || (isPrevent && !record.userSecretName) || isPrevent"
            size="small"
            v-model:checked="record.isEnabled"
          />
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a
            class="eidtRecords"
            :class="{ disable: editAble }"
            @click="eidtRecord(record)"
            >{{ oparation[0] }}</a
          >
          <a
            class="eidtRecords"
            :class="{ disable: !btnPerm.includes('userPermSetAble') || record.id === userId }"
            @click="eidtPerssion(record)"
            >{{ oparation[1] }}</a
          >
          <a
            class="eidtRecords"
            :class="{ disable: !btnPerm.includes('userPermViewAble') }"
            @click="openAllAuth(record)"
            >{{ oparation[2] }}</a
          >
          <a
            class="eidtRecords"
            :class="{ disable: resPassWordAble }"
            @click="resetPassword(record)"
            >{{ oparation[3] }}</a
          >
          <a-popconfirm
            placement="topRight"
            :disabled="record.id === userId || deleteAble"
            @confirm="confirmDelete(record)"
          >
            <template #title>
              <p style="width: 197px">是否删除此成员</p>
            </template>
            <a
              :class="{ disable: deleteAble || record.id === userId }"
              >{{ oparation[4] }}</a
            >
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="deleteSelectedAll"
          :disabled="!rowSelection.length || deleteAble"
          >删除</a-button
        >
        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="openSelectedAll('1')"
          :disabled="!rowSelection.length"
          >启用</a-button
        >
        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="openSelectedAll('2')"
          :disabled="!rowSelection.length"
          >禁用</a-button
        >
      </template>
    </baseTable>

    <!-- 新建用户模态框 -->
    <base-modal
      :width="modAlProps.width"
      :isVisible="isVisible"
      :title="modAlProps.title"
      :buttons="buttons"
      @handleOk="buttonMessage"
      @handleCancle="isVisible = false"
      class="usermanage_modal"
    >
      <template v-slot:body>
        <a-form
          name="advanced_search"
          class="ant-advanced-search-form"
          autoComplete="off"
          :model="formState"
          ref="userManageFrom"
          v-if="isVisible"
        >
          <template v-if="isAddOrEdit">
            <a-form-item
              class="user-input"
              v-if="modAlProps.title === '新建用户'"
              :name="['username', 'value']"
              :label="formState.username.label"
              :rules="[formState.username.rule]"
            >
              <a-input
                placeholder="不超过25个字"
                v-model:value="formState.username.value"
                autocomplete="new-password"
                show-count
                :maxlength="25"
                allow-clear
              />
            </a-form-item>
            <a-form-item
              class="user-input"
              v-else
              :name="['username', 'value']"
              :label="formState.username.label"
              :rules="[formState.username.rule]"
            >
              {{ formState.username.value }}
            </a-form-item>
            <a-form-item
              v-if="modAlProps.title === '新建用户'"
              :name="['password', 'value']"
              :label="formState.password.label"
              :rules="[formState.password.rule]"
            >
              <a-input-password
                placeholder="请输入"
                autocomplete="new-password"
                v-model:value="formState.password.value"
                allow-clear
              />
            </a-form-item>
            <a-form-item
              v-if="modAlProps.title === '新建用户' && formState.password.value"
              :name="['repassword', 'value']"
              :label="formState.repassword.label"
              :rules="[formState.repassword.rule]"
            >
              <a-input-password
                placeholder="请输入"
                v-model:value="formState.repassword.value"
                ref="password1"
                allow-clear
              />
            </a-form-item>
            <a-form-item
              :name="['org', 'value']"
              :label="formState.org.label"
              :rules="[formState.org.rule]"
            >
              <a-tree-select
              v-if="modAlProps.title === '新建用户' || editUserId !== userId"
                v-model:value="formState.org.value"
                ref="usermanage_treeSelect"
                show-search
                :dropdown-style="{ maxHeight: '500px', overflow: 'auto' }"
                placeholder="请选择"
                allow-clear
                treeNodeFilterProp="name"
                :fieldNames="{
                  children: 'children',
                  label: 'name',
                  value: 'id',
                }"
                tree-default-expand-all
                :tree-data="orgTreeData"
                @select="selectTreeData"
              >
              </a-tree-select>
              <span v-else>{{ editUserOrgName }}</span>
            </a-form-item>

            <a-form-item :name="['orgVir', 'value']" :label="formState.orgVir.label">
              <a-select
                placeholder="请选择"
                @change="onSelectOrg1"
                v-model:value="formState.orgVir.value"
                :options="virOrgIdsOptions"
                allow-clear
              ></a-select>
            </a-form-item>
            <a-form-item
              :name="['realname', 'value']"
              :label="formState.realname.label"
              :rules="[formState.realname.rule]"
            >
              <a-input
                placeholder="请输入"
                v-model:value="formState.realname.value"
                allow-clear
              />
            </a-form-item>
            <a-form-item
              :name="['telephone', 'value']"
              :label="formState.telephone.label"
              :rules="[formState.telephone.rule]"
            >
              <a-input
                placeholder="请输入"
                v-model:value="formState.telephone.value"
                allow-clear
              />
            </a-form-item>
            <a-form-item
              :name="['phone', 'value']"
              :label="formState.phone.label"
              :rules="[formState.phone.rule]"
            >
              <a-input
                placeholder="请输入"
                v-model:value="formState.phone.value"
                allow-clear
              />
            </a-form-item>
            <a-form-item
              :name="['email', 'value']"
              :label="formState.email.label"
              :rules="[formState.email.rule]"
            >
              <a-input
                placeholder="请输入"
                v-model:value="formState.email.value"
                allow-clear
              />
            </a-form-item>
            <a-form-item
              :name="['sequrity', 'value']"
              :label="formState.sequrity.label"
              v-if="formState.id && isPrevent"
            >
              <!-- <a-select placeholder="请选择" @change="onSelectSequrity1" v-model:value="formState.sequrity.value"
                :options="userSecretIdOptions" allow-clear></a-select> -->
              <span>{{ formState.sequrity.value }}</span>
            </a-form-item>
            <a-form-item :label="formState.contentViewCtl.label" class="contentViewCtl">
              <a-radio-group v-model:value="formState.contentViewCtl.value">
                <a-radio :value="1">无限制</a-radio>
                <a-radio :value="2">用户组织创建的内容</a-radio>
                <a-radio :value="3">用户创建的内容</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item
              :name="['status', 'value']"
              :label="formState.status.label"
              :rules="[formState.status.rule]"
            >
              <a-switch
                size="small"
                :disabled="
                  formState.id === userId || (isPrevent && !formState.sequrity.value)
                "
                v-model:checked="formState.isEnabled"
              />
            </a-form-item>
          </template>
          <template v-else-if="isResetPassword">
            <a-form-item
              class="user-input"
              :style="{ 'margin-bottom': '15px' }"
              :label="formState.username.label"
            >
              <p>{{ formState.username.value }}</p>
            </a-form-item>
            <a-form-item
              class="password-item"
              :name="['password', 'value']"
              :label="formState.password.label"
              :rules="[formState.password.rule]"
            >
              <a-input-password
                placeholder="请输入"
                v-model:value="formState.password.value"
                ref="password1"
                allow-clear
              />
            </a-form-item>
            <a-form-item
              class="password-item"
              :name="['repassword', 'value']"
              :label="formState.repassword.label"
              :rules="[formState.repassword.rule]"
            >
              <a-input-password
                placeholder="请输入"
                v-model:value="formState.repassword.value"
                allow-clear
              />
            </a-form-item>
          </template>
          <template v-else>
            <a-form-item
              :name="['batchUserManage', 'value']"
              :label="formState.batchUserManage.label"
              :rules="[formState.batchUserManage.rule]"
            >
              <upload
                :action="props_upload.action"
                :fileList="props_upload.fileList"
                :accept="props_upload.accept"
                :directory="props_upload.directory"
                :isAutoUpload="props_upload.isAutoUpload"
                :listType="props_upload.listType"
                @uploadChangeFinished="uploadFiles"
              >
              </upload>
            </a-form-item>
            <a-form-item label="重复用户:" :rules="[{ required: true }]">
              <a-radio-group v-model:value="formState_redio">
                <a-radio value="0">覆盖重复项</a-radio>
                <a-radio value="1">跳过重复项</a-radio>
              </a-radio-group>
            </a-form-item>
          </template>
        </a-form>
      </template>
    </base-modal>
    <base-modal
      :width="modAlProps.width"
      :cancleText="'关闭'"
      :isVisible="isSeeAllAuth"
      :buttons="buttons"
      :title="modAlProps.title"
      @handleCancle="isSeeAllAuth = false"
      class="usermanage_modal"
    >
      <template v-slot:body>
        <div class="permission-content">
          <baseTabs
            @changeTabs="changeTopTabs"
            :activeKey="tabActive"
            :tabsList="tabsList"
            v-slot="{ item }"
          >
            <!-- 站群权限 -->
            <div v-show="tabActive === 1">
              <div class="add-site-tip-top">
                <a-checkbox v-model:checked="addSitechecked" disabled
                  >增量站点</a-checkbox
                >
                <a-tooltip placement="right">
                  <template #title>
                    <span>选中后，用户可拥有后续新增子站点的权限</span>
                  </template>
                  <i
                    class="iconfont icon-hint1"
                    style="font-size: 16px; margin-left: 8px"
                  >
                  </i>
                </a-tooltip>
              </div>
              <base-tree
                :height="656"
                :checkedKeys="checkedKeys"
                :treeData="treeData"
              ></base-tree>
            </div>
            <!-- 菜单权限 -->
            <div v-show="tabActive === 2">
              <div class="add-site">
                <div class="add-site-tip">
                  <a-checkbox>增量菜单</a-checkbox>
                  <a-tooltip placement="right">
                    <template #title>
                      <span>选中后，用户可拥有后续新增子站点的权限</span>
                    </template>
                    <i
                      class="iconfont icon-hint1"
                      style="font-size: 16px; margin-left: 8px"
                    >
                    </i>
                  </a-tooltip>
                </div>
              </div>
              <!-- <base-tree :height="656" :treeData='menusTree'></base-tree> -->
            </div>
            <!-- 站点权限 -->
            <div v-show="tabActive === 3">
              <div class="site-tab">
                <!-- 站点权限表格展示部分 -->
                <!-- <treeTable :columns="columns.sitePressionColumns" :dataSource="configData.sitRecords" :rowSelection="1"
                :isSelect="true" ref="baseTables">
                <template #headerCell="{ column, record }">
                  <a-checkbox v-model="text">{{ column.title }}</a-checkbox>
                </template>
                <template #bodyCell="{ column, record }">
  
                  <a-checkbox v-if="column.dataIndex === 'sitename'" v-model="text">
                    <div v-if="record.name === 'add'">
                      增量栏目
                      <a-tooltip placement="right">
                        <template #title>
                          <span>选中后，用户可拥有后续新增子站点的权限</span>
                        </template>
                        <i class="iconfont icon-hint1" style="font-size: 16px; margin-left: 8px">
                        </i>
                      </a-tooltip>
                    </div>
                    <div v-else>{{ record.name }}</div>
                  </a-checkbox>
                  <a-checkbox v-else v-model="text"></a-checkbox>
                </template>
              </treeTable> -->
              </div>
            </div>
            <!-- 栏目权限 -->
            <div v-show="tabActive === 4">
              <div class="section-tab">
                <!-- 栏目权限表格展示部分 -->
                <!-- <treeTable :columns="columns.sectionColumns" :dataSource="configData.records" :rowSelection="1"
                :isSelect="true" ref="baseTables">
                <template #headerCell="{ column, record }">
                  <a-checkbox v-model="text">{{ column.title }}</a-checkbox>
                </template>
                <template #bodyCell="{ column, record }">
  
                  <a-checkbox v-if="column.dataIndex === 'sectionname'" v-model="text">{{ record.name }}</a-checkbox>
                  <a-checkbox v-else v-model="text"></a-checkbox>
                </template>
              </treeTable> -->
              </div>
            </div>
            <!-- 文档权限 -->
            <div v-show="tabActive === 5">
              <div class="document-tab">
                <!-- 文档权限表格展示部分 -->
                <!-- <treeTable :columns="columns.documentColumns" :dataSource="configData.records" :rowSelection="1"
                :isSelect="true" ref="baseTables">
                <template #headerCell="{ column, record }">
                  <a-checkbox v-model="text">{{ column.title }}</a-checkbox>
                </template>
                <template #bodyCell="{ column, record }">
  
                  <a-checkbox v-if="column.dataIndex === 'sectionname'" v-model="text">{{ record.name }}</a-checkbox>
                  <a-checkbox v-else v-model="text"></a-checkbox>
                </template>
              </treeTable> -->
              </div>
            </div>
          </baseTabs>
        </div>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts">
export default {
  name: "成员",
};
</script>
<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, createVNode, computed } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import upload from "@/components/upload/fileUpload.vue";
import { Modal, message, SelectProps } from "ant-design-vue";
import request from "@/api/index";
import baseTabs from "@/components/tabs/baseTabs.vue";
import baseTree from "@/components/tree/baseTree.vue";
import getters from "@/store/getters";
import { scrollType, modeProp, detailDataItemType, TreePropsList } from "@/type.d";
import globalMethods from "@/utils/global";
import { checkuserManage } from "./formRuler";
import { useRouter } from "vue-router";
import { encrypt3DES, decrypt3DES } from "@/utils/cryptojs";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { routerPerm } from "@/utils/common";
// type
type userDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}

//data
const btnPerm = ref<any[]>([]);
const creatAble = ref<any>(false); // 按钮权限
const importAble = ref<any>(false);
const downloadAble = ref<any>(false);
const editAble = ref<any>(false);
const resPassWordAble = ref<any>(false);
const deleteAble = ref<any>(false);
let userManagesColumns = ref(JSON.parse(JSON.stringify(columns.userManagesColumns)));
let userId = getters.userInfo().userId;
const editUserId = ref<any>(null);
const editUserOrgName = ref<any>(null);

const router = useRouter();
//筛选表格项
const isOpen = ref<boolean>(true); //是否展开或收起
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
let resData: dataSourceType = reactive({
  //头部筛选请求参数格式
  pageNumber: 0,
  pageSize: 10,
  name: "",
  orgId: 0 || "",
  virOrgId: 0 || "",
  pageSort: 0,
  status: "",
  userSecretId: 0,
});
//树形结构数据
const treeData: TreePropsList[] = [];

const checkedKeys = ref<string[]>([]);

const statusOptions = [
  { value: "全部", status: "" },
  { value: "启用", status: 1 },
  { value: "禁用", status: 0 },
];
const statusHeaderValue = ref<string>("全部");
const orgVirValue = ref<string>("全部");
const sequrityValue = ref<string>("全部");
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
// const searchUserManage = ref<string | number>(''); //搜索框
const oparation = ref<string[]>(["编辑", "权限设置", "查看全部权限", "重置密码", "删除"]); //站点表格操作项

//表格数据
let userData = reactive<userDataType>({ total: 0, size: 10, records: [] });
const userManageBaseTables = ref<any>(null); // basetable的ref
let rowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);

//新增或编辑选择项
const orgOptions = ref<SelectProps["options"]>([]);
const orgVirOptions = ref<SelectProps["options"]>([]);
const sequrityOptions = ref<SelectProps["options"]>([]);
const userSecretIdOptions = ref<SelectProps["options"]>([]);
const virOrgIdsOptions = ref<SelectProps["options"]>([]);
const orgTreeData = ref<detailDataItemType>([]); //下拉选择树
const orgTreeDataHeader = ref<detailDataItemType>([]); //下拉选择树
const siteDetail_treeSelect = ref<any>(null);
const selectOrgvalue = ref<string>("全部"); //头部选择所选组织
// 模态框数据
const userManageFrom = ref<any>("userManageFrom");
const orgVirNameValue = ref<string>("");
const isAddOrEdit = ref<boolean>(true); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
const isResetPassword = ref<boolean>(false);
const isSeeAllAuth = ref<boolean>(false); // 判断是否查看全部权限
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建用户",
});
// const validatePass = ref<any>("userManageFrom");
// const userManageFrom = ref<any>("userManageFrom");
// 重复密码校验

const password1 = ref<any>(null);

const validatepasssure = (_rule: dataSourceType = {}, value: any) => {
  if (value === "") {
    return Promise.reject(`重复密码不能为空！`);
  } else if (value !== formState.password.value) {
    return Promise.reject(`两次输入密码不一致！`);
  } else {
    return Promise.resolve();
  }
};
const validatePass = async (_rule: dataSourceType = {}, value: any) => {
  if (value === "") {
    return Promise.reject(`登录密码不可为空！`);
  } else {
    let data = await request.fetchMemberPasswordCheck({
      password: encrypt3DES(value),
    });
    if (data.code == "00000 00000") {
      return Promise.resolve();
    } else {
      return Promise.reject(`${data.message}`);
    }
  }
};
const formState = reactive<dataSourceType>({
  username: {
    value: "",
    rule: {
      required: true,
      validator: checkuserManage,
      trigger: ["blur"],
      msg1: "用户名不可为空！",
      msg2: "用户名已存在！",
      api: "fetchUserNameValid",
      params: { id: null },
    },
    id: "",
    label: "用户名",
  },

  password: {
    value: "",
    rule: {
      required: true,
      validator: validatePass,
      trigger: ["blur"],
      msg1: "登录密码不可为空！",
      msg2: "登录密码错误！",
      // api: "fetchSensitiveWordTableUnique",
      params: {},
    },
    label: "登录密码",
  },

  repassword: {
    value: "",
    rule: {
      required: true,
      validator: validatepasssure,
      trigger: ["blur"],
      msg1: "登录密码不可为空！",
      msg2: "登录密码错误！",
      // api: "fetchSensitiveWordTableUnique",
      params: {},
    },
    label: "重复密码",
  },
  org: {
    value: "",
    rule: {
      required: true,
      validator: checkuserManage,
      trigger: ["blur"],
      message: "所属组织不可为空！",
      api: "",
      params: {},
    },
    label: "所属组织",
  },
  orgVir: {
    value: "",
    rule: {
      required: false,
      params: {},
    },
    label: "虚拟组织",
  },
  sequrity: {
    value: "",
    rule: {
      required: false,
      params: {},
    },
    label: "人员密级",
  },
  realname: {
    value: "",
    rule: {
      required: false,
      params: {},
    },
    label: "真实姓名",
  },
  telephone: {
    value: "",
    rule: {
      required: false,
      params: {},
    },
    label: "座机号",
  },
  phone: {
    value: "",
    rule: {
      required: false,
      params: {},
    },
    label: "手机号",
  },
  email: {
    value: "",
    rule: {
      required: false,
      params: {},
    },
    label: "电子邮件",
  },
  contentViewCtl: {
    value: 1,
    rule: {
      required: false,
      params: {},
    },
    label: "内容查看权限",
  },
  status: {
    value: "",
    rule: {
      required: false,
      params: {},
    },
    label: "用户状态",
  },

  batchUserManage: {
    //批量上传
    value: {}, //接收批量上传文件传来的emit('');
    trigger: ["change", "blur"],
    rule: { required: true, message: "上传文件不可为空！" },
    label: "上传文件:",
  },
  isEnabled: false,
  orgId: "",
  userSecretId: "",
  virOrgIds: [],
  id: "",
});

//权限tab切换
const tabsList = [
  { tabName: "站群权限", key: 1 },
  { tabName: "菜单权限", key: 2 },
  { tabName: "站点权限", key: 3 },
  { tabName: "栏目权限", key: 4 },
  { tabName: "文档权限", key: 5 },
];
const tabActive = ref<number>(1);
const addSitechecked = ref<boolean>(true);
// 模板文件上传配置
const props_upload = reactive<dataSourceType>({
  action: "", //
  accept: "xlsx,xls",
  directory: false,
  listType: "text",
  fileList: [], // 已上传的文件
  isAutoUpload: false, //是否自动上传
});
let formState_redio = ref<string | number>("0");
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
const isPrevent = ref<Boolean>(true);
// computed
rowSelection = computed(() => {
  let index = userManageBaseTables.value.selectedRowKeys.findIndex(
    (item: number) => item === userId
  );
  if (index !== -1) {
    userManageBaseTables.value.selectedRowKeys.splice(index, 1);
  }
  return userManageBaseTables.value.selectedRowKeys;
});

//methods

//重置筛选项
const resetOptions = () => {
  resData.name = "";
  resData.orgId = 0;
  selectOrgvalue.value = "全部";
  resData.virOrgId = 0;
  orgVirValue.value = "全部";
  resData.userSecretId = null;
  sequrityValue.value = "全部";
  resData.status = null;
  statusHeaderValue.value = "全部";
  search()
  // resData.status = "";
  // resData.virOrgId = "";
};

//改变头部状态
const selectHeaderStatus = (e: string, options: any) => {
  statusHeaderValue.value = e;
  resData.status = options?.status.toString() ? options.status : "";
  search()
};

//展示或者隐藏筛选框
const openorclose = () => {
  isOpen.value = !isOpen.value;
  if (!isOpen.value) {
    let obj = getTableScroll(74, "userManage", 212);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  } else {
    let obj = getTableScroll(74, "userManage", 150);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  }
};

//搜索
const search = () => {
  resData.pageNumber = 0;
  getRdecord();
};

const switchChange = async (record: dataSourceType) => {
  //开启关闭启用
  request[record.isEnabled ? "fetchMemberEnable" : "fetchMemberDisable"]({
    ids: [record.id],
  })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

const addRecord = async () => {
  //新加成员模态框条件修改
  //添加成员数据
  formState.username.rule.params.id = null;
  formState.username.value = "";
  formState.password.value = "";
  formState.repassword.value = "";
  formState.realname.value = "";
  formState.contentViewCtl.value = 1;
  formState.telephone.value = "";
  formState.phone.value = "";
  formState.email.value = "";
  formState.org.value = null;
  formState.orgVir.value = null;
  formState.sequrity.value = null;
  formState.id = "";
  formState.isEnabled = true;
  isAddOrEdit.value = true;
  modAlProps.title = "新建用户";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  isVisible.value = true;
  isResetPassword.value = false;
};
const usermanage_treeSelect = ref<any>(null);
const eidtRecord = async (item: dataSourceType) => {
  editUserId.value = item.id
  if (editAble.value) return;
  //编辑成员数据
  const data = (await request.fetchUserDetail({ id: item.id })) || {};
  nextTick(() => {
    formState.username.value = data.userName;
    formState.realname.value = data.realName;
    formState.telephone.value = data.fixPhone;
    formState.phone.value = data.userPhone;
    formState.email.value = data.userEmail;
    formState.org.value = data.orgId;
    formState.orgVir.value = data.virOrgIds[0];
    formState.virOrgIds = item.virOrgIds;
    formState.userSecretId = data.userSecretId;
    formState.sequrity.value = data.userSecretName;
    formState.isEnabled = data.isEnabled;
    formState.username.rule.params.id = data.id;
    formState.contentViewCtl.value = +data.contentViewCtl;
    formState.id = data.id;
    formState.orgId = data.orgId;
    editUserOrgName.value = data.orgName
    isAddOrEdit.value = true;
    modAlProps.title = "编辑成员";
    usermanage_treeSelect.value.focus();
    usermanage_treeSelect.value.blur();
    buttons.value = [
      {
        text: "保存",
        "html-type": "submit",
        keepAlive: true,
      },
    ];
    isResetPassword.value = false;
    isVisible.value = true;
  });
};
const eidtPerssion = (record: dataSourceType) => {
  if (record.id === userId || !btnPerm.value.includes("userPermSetAble")) return;
  //设置权限
  router.push({
    path: "/system/userManage/permissionSettings",
    query: {
      userId: record.id,
      orgId: record.orgId,
      allPermissions: 0,
      userName: record.userName,
    },
  });
};
const openAllAuth = (record: dataSourceType) => {
  if (!btnPerm.value.includes("userPermViewAble")) return;
  //查看全部权限
  // isSeeAllAuth.value = true
  // modAlProps.title = "查看全部权限";
  // modAlProps.width = "L";
  router.push({
    path: "/system/userManage/permissionSettings",
    query: {
      userId: record.id,
      orgId: record.orgId,
      allPermissions: 1,
      disabled: 1,
      userName: record.userName,
    },
  });
};
const resetPassword = (record: dataSourceType) => {
  if (resPassWordAble.value) return;
  //重置密码
  formState.username.value = record.userName;
  formState.password.value = "";
  formState.repassword.value = "";
  formState.id = record.id;
  modAlProps.title = "重置密码";
  buttons.value = [
    {
      text: "重置",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  isResetPassword.value = true;
  isAddOrEdit.value = false;
  isVisible.value = true;
};

const batchAddRecord = async () => {
  //批量上传
  isVisible.value = true;
  isAddOrEdit.value = false;
  modAlProps.title = "批量导入用户";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

// 新添或编辑成员调取接口
const buttonMessage = async (msg: dataSourceType) => {
  //保存
  userManageFrom.value
    .validate()
    .then(() => {
      let params: dataSourceType = {
        // dealWithType: +formState_redio.value,
        fixPhone: formState.telephone.value,
        isEnabled: formState.isEnabled,
        orgId: formState.orgId,
        password: encrypt3DES(formState.password.value),
        repeatePassword: encrypt3DES(formState.repassword.value),
        realName: formState.realname.value,
        userEmail: formState.email.value,
        userName: formState.username.value,
        userPhone: formState.phone.value,
        userSecretId: formState.userSecretId,
        id: formState.id,
        virOrgIds: formState.virOrgIds,
        contentViewCtl: +formState.contentViewCtl.value,
      };

      let type: string = modAlProps.title.includes("批量")
        ? ""
        : modAlProps.title.includes("编辑")
        ? "Edit"
        : modAlProps.title.includes("重置")
        ? "Reset"
        : "Add";

      if (type) {
        request[
          type === "Edit"
            ? "fetchUserUpdate"
            : type === "Add"
            ? "fetchMemberAdd"
            : "fetchUserResetpwd"
        ](params)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              getRdecord();
              message.success(res.message);
              isResetPassword.value = false;

              isVisible.value = msg.text == "保存" || msg.text == "重置" ? false : true;

              props_upload.fileList = [];
              userManageFrom.value.resetFields();
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      } else {
        const param = new FormData(); // 创建form对象
        // param.append("files", options.file, options.file.name); // 通过append向form对象添加数据
        param.append(
          "file",
          formState.batchUserManage.value.file,
          formState.batchUserManage.value.file.name
        ); // 通过append向form对象添加数据
        param.append("ealWithType", `${formState_redio.value}`);
        request
          .fetchUserImport(param)
          .then((res: dataSourceType) => {
            //直接调接口
            if (res.code === "00000 00000") {
              props_upload.fileList.push(formState.batchUserManage.value);
              getRdecord();
              message.success(res.message);
              isResetPassword.value = false;
              isVisible.value = msg.text == "保存" || msg.text == "重置" ? false : true;
              props_upload.fileList = [];
              userManageFrom.value.resetFields();
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      }
    })
    .catch(() => {});
};

//头部选择所选组织
const selectTreeDataHeader = async (id: string | number, record: any) => {
  resData.orgId = id ? id : 0;
  search()
  // selectOrgvalue.value = record.name ? record.name : "全部";
};

//新建或编辑选择所选组织
const selectTreeData = async (id: string | number, record: any) => {
  // if (id === record.id) { // 说明点击了的是当前的已经选中的选项了，无需做数据变动;
  //   formState.orgId = id
  // }
  formState.orgId = id ? id : null;
  // formState.org.value = record.name ;
};

//改变权限内容tab切换
const changeTopTabs = (activeKey: number) => {
  tabActive.value = activeKey;
};

// 删除单个成员
const confirmDelete = async (item: any) => {
  if (deleteAble.value) return;
  console.log(item, "item");
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};
//删除已选所有成员
const deleteSelectedAll = async () => {
  let keys: (string | number)[] = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "是否批量删除选中的成员",
      content: "",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};
//批量启用或禁用用户
const openSelectedAll = async (type: string | number) => {
  let keys: (string | number)[] = rowSelection.value;
  request[type == 1 ? "fetchMemberEnable" : "fetchMemberDisable"]({ ids: keys })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRdecord();
        rowSelection.value = userManageBaseTables.value.selectedRowKeys = [];
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除成员
  await request.fetchMemberDetele({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      getRdecord();
    } else {
      message.error(res.message);
    }
  });
};

const getRdecord = async () => {
  // 获取表格数据
  const data: {} = {
    pageNumber: resData.pageNumber || 1,
    pageSize: resData.pageSize || 10,
    name: resData.name || "",
    orgId: resData.orgId || "",
    virOrgId: resData.virOrgId || "",
    pageSort: resData.pageSort || "",
    status: resData.status,
    userSecretId: resData.userSecretId || "",
  };
  const telData = (await request.fetchUserPage(data)) || {};
  nextTick(() => {
    let reqData = telData;
    let sourceData = {};
    const records: any[] = [];
    reqData?.records?.map((item: any, index: number) => {
      sourceData = {
        authAble: item.authAble,
        deleteAble: item.deleteAble,
        editAble: item.editAble,
        id: item.id,
        isEnabled: item.isEnabled,
        orgId: item.orgNum,
        orgName: item.orgName,
        resetPwdAble: item.memberManagerAble,
        realName: item.realName,
        userName: item.userName,
        userSecretId: item.userSecretId,
        userSecretName: item.userSecretName,
        virOrgIds: item.creavirOrgIdsteUser,
        virOrgNames: item.virOrgNames,
        disableReason: item.disableReason,
      };
      records.push(sourceData);
    });
    userData.total = reqData.total;
    userData.size = reqData.size;
    userData.records = records;
    userManageBaseTables.value.selectedRowKeys = [];
    nextTick(() => {
      let obj = getTableScroll(74, "userManage", 150);
      scroll.y = obj.y;
      scroll.isFixed = obj.isFixed;
    });
  });
};

const getOrgCurvirorg = async () => {
  const data = (await request.fetchUserOrgCurvirorg({})) || [];
  data.length &&
    data.forEach((item: dataSourceType) => {
      virOrgIdsOptions.value?.push({ label: item.name, value: item.id });
      item.value = item.name;
    });

  orgVirOptions.value = [{ name: "全部", id: 0, value: "全部" }, ...data];
};
const getAllUserSecretList = async () => {
  const data = (await request.fetchAllUserSecretList({})) || [];
  data.length &&
    data.forEach((item: dataSourceType) => {
      userSecretIdOptions.value?.push({ label: item.name, value: item.id });
      item.value = item.name;
    });
  sequrityOptions.value = [{ name: "全部", id: 0, value: "全部" }, ...data];
};

//获取当前用户可见组织树
const fetchUserOrgTree = async () => {
  const data = (await request.fetchUserOrgTree()) || [];
  orgTreeData.value = [...data.filter((item: dataSourceType) => item.orgType == 1)];
  orgTreeDataHeader.value = [
    { name: "全部", id: 0 },
    ...data.filter((item: dataSourceType) => !item.authAble),
  ];
  selectOrgvalue.value = selectOrgvalue.value || orgTreeDataHeader.value[0].name;
};
const downloadtemp = async () => {
  if (downloadAble.value) return;
  // 下载模板
  await request
    .fetchUserDownloadTemplate()
    .then((res: any) => {
      globalMethods.downloadFile(res, "下载成员模板文件.xls");
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  (resData.pageNumber = data.pageCurrent),
    (resData.pageSize = data.pageSize),
    getRdecord();
};
const uploadFiles = async (fileObj: dataSourceType) => {
  console.log(fileObj, "fileObj");
  // 配置上传文件所需参数
  formState.batchUserManage.value = fileObj;
};

//头部选择关联的虚拟组织
const onSelectOrg = (val: string, option: any) => {
  resData.virOrgId = option?.id ? option.id : 0;
  search()
};
//选择关联的虚拟组织
const onSelectOrg1 = (val: string, option: any) => {
  formState.virOrgIds = val ? [val] : null;
  search()
};
//头部选择人员密级
// const onSelectSequrity = (val: string, option: any) => {
//   resData.userSecretId = option?.id ? option.id : null;
//   search()
// };
//新增编辑选择人员密级
const onSelectSequrity1 = (val: string, option: any) => {
  formState.userSecretId = val ? val : "";
};
// 检测是否开启密级管理
const isOpenPrevent = async () => {
  isPrevent.value = await request.isOpenPrevent();
  userManagesColumns.value = JSON.parse(JSON.stringify(columns.userManagesColumns));
  // if (isPrevent.value) {
  //   userManagesColumns.value.splice(4, 1);
  // }
};
//onmounted
onMounted(async () => {
  btnPerm.value = routerPerm();
  routerPerm().includes("creatAble")
    ? (creatAble.value = false)
    : (creatAble.value = true);
  routerPerm().includes("importAble")
    ? (importAble.value = false)
    : (importAble.value = true);
  routerPerm().includes("downloadAble")
    ? (downloadAble.value = false)
    : (downloadAble.value = true);
  routerPerm().includes("editAble") ? (editAble.value = false) : (editAble.value = true);
  routerPerm().includes("resPassWordAble")
    ? (resPassWordAble.value = false)
    : (resPassWordAble.value = true);
  routerPerm().includes("deleteAble")
    ? (deleteAble.value = false)
    : (deleteAble.value = true);

  fetchUserOrgTree();
  getRdecord();
  getOrgCurvirorg();
  getAllUserSecretList();
  isOpenPrevent();
});
</script>
<style lang="scss" scoped>
.userManage {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .userManage_button {
    padding-bottom: 16px;
    display: flex;
    align-items: center;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .importButton:hover {
      color: #4892fa;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;

      .icon-search {
        font-size: 15px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  .select-content {
    width: 100%;
    background: rgba(0, 0, 0, 0.02);
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    padding: 24px 24px 0;
    margin-bottom: 24px;

    .select-item {
      width: 354px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: flex-end;
      margin-bottom: 24px;

      .title {
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.85);
      }
    }

    .option-content {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: flex-end;
      margin-bottom: 24px;
      width: 354px;
    }

    .option-content .openorclose {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-left: 16px;
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #1f6ded;

      .iconfont {
        margin-left: 5px;
      }
    }
  }

  :deep(.ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}

.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}
.userManagefixed {
  height: calc(100% - 120px);
}

.permission-content {
  padding-bottom: 24px;

  .add-site {
    display: flex;
    flex-direction: column;
    padding-top: 22px;
    padding-bottom: 8px;
    font-size: 14px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);

    .add-site-tip {
      margin-top: 4px;
      display: flex;
      flex-direction: row;
      align-items: center;
    }
  }

  .add-site-tip-top {
    padding-top: 22px;
    padding-bottom: 8px;
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .section-tab {
    padding-top: 24px;
  }

  .document-tab {
    padding-top: 24px;
  }
}

.download-btn {
  font-weight: 400;
  margin-left: 16px;
  line-height: 22px;
  height: 22px;
  font-size: 14px;
}

.download-btn:hover {
  color: #4892fa;
}

::v-deep(.ant-table-body) {
  .ant-table-cell:nth-child(7) {
    text-align: right;
  }
}

::v-deep(.select-item .ant-select) {
  width: 241px;
}

::v-deep(.ant-checkbox-disabled + span) {
  color: rgba(0, 0, 0, 0.85);
}

::v-deep(.option-content .ant-btn) {
  width: 60px;
}

:deep(.ant-form-item) {
  width: 596px;
  display: flex;

  // margin-left: 28px;

  .ant-form-item-control {
    width: 312px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 98px;
    text-align: right;
  }
}

.contentViewCtl {
  width: 100%;

  :deep(.ant-form-item-control) {
    width: 400px;
    margin-left: 4px;
    flex: unset;
  }
}

::v-deep(.user-input .ant-form-item-control) {
  width: 490px;
  margin-left: 4px;
  flex: unset;
}

::v-deep(.password-item .ant-form-item-control) {
  width: 344px;
  margin-left: 4px;
  flex: unset;
  padding-bottom: 10px;
}

:deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
  margin-top: -10px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}

::v-deep(.ant-tabs-tab) {
  padding: 0 0 10px 0;
}

::v-deep(::-webkit-scrollbar) {
  height: 8px;
}

::v-deep(.ant-tree-list .ant-tree-list-scrollbar) {
  display: none !important;
}

::v-deep(::-webkit-scrollbar-track) {
  box-shadow: none;
}

::v-deep(.ant-tree-list-scrollbar-thumb) {
  background: rgba(0, 0, 0, 0.15) !important;
}

::v-deep(.ant-checkbox + span) {
  padding-left: 12px;
  padding-right: 0;
}

::v-depp(.ant-table-wrapper) {
  margin-top: 24px;
}
</style>
<style>
/* .AtreeSelect .ant-select-selector {
  width: 144px;
  transition: width 0.1s cubic-bezier(0.075, 0.82, 0.165, 1);
}

.AtreeSelect .ant-select-open .ant-select-selector {
  width: 300px;
} */

.usermanage_modal .AtreeSelect .ant-select-selector .ant-select-selection-item {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.usermanage_modal .ant-modal-body {
  margin-bottom: -32px;
}

.section-tab .ant-table-wrapper {
  margin-top: 24px;
}

.site-tab .ant-table-wrapper {
  margin-top: 24px;
}

.document-tab .ant-table-wrapper {
  margin-top: 24px;
}

.ant-tooltip {
  max-width: 700px;
}
</style>
